const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('koa2-cors')
const { verifyToken } = require('./token.config')

app.use(cors({
  origin: ['http://localhost:3000'], // 设置跨域地址
}))


const index = require('./routes/index')
const users = require('./routes/users')
const questions = require('./routes/questions')
const mall = require('./routes/mall')
const chat = require('./routes/chat')
const previousFonc = require('./routes/previousFonc')
const underDevelopment = require('./routes/underDevelopment')
const leaveMessage = require('./routes/leaveMessage')
const leaveMessageRank = require('./routes/leaveMessageRank')
const games = require('./routes/games')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(questions.routes(), questions.allowedMethods())
app.use(mall.routes(), mall.allowedMethods())
app.use(chat.routes(), chat.allowedMethods())
app.use(previousFonc.routes(), previousFonc.allowedMethods())
app.use(underDevelopment.routes(), underDevelopment.allowedMethods())
app.use(leaveMessage.routes(), leaveMessage.allowedMethods())
app.use(leaveMessageRank.routes(), leaveMessageRank.allowedMethods())
app.use(games.routes(), games.allowedMethods())

// 使用token验证中间件
// 一定要放在routes中间件下面，先验证token，再执行请求
app.use(verifyToken) 

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
